//
//  PRAddNewRecordVC.m
//  PearRich
//
//  Created by 谢黎鹏 on 2020/1/12.
//  Copyright © 2020年 谢黎鹏. All rights reserved.
//

#import "PRAddNewRecordVC.h"
#import "PRAddNewRecordCell.h"
#import <PGDatePicker/PGDatePickManager.h>
#import "PRClientNameTableView.h"
#import "PRClientDataModel.h"
@interface PRAddNewRecordVC ()<PGDatePickerDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UIView *goodContainView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *goodContainHeight;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UIButton *choseTimeBtn;
@property (weak, nonatomic) IBOutlet UIButton *sendedBtn;
@property (weak, nonatomic) IBOutlet UIButton *unSendBtn;
@property (weak, nonatomic) IBOutlet UIButton *unPayBtn;
@property (weak, nonatomic) IBOutlet UIButton *payedBtn;
@property (weak, nonatomic) IBOutlet QMUITextView *remarkTV;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *botHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHeight;
@property(nonatomic,assign)BOOL isChoseTime;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *choseBtnWidth;
@property (weak, nonatomic) IBOutlet UIButton *currentTimeBtn;
@property(nonatomic,retain)UIButton * sendSelBtn,* paySelBtn;
@property (weak, nonatomic) IBOutlet UILabel *orderCreateTimeLab;
@property(nonatomic,retain)UITableView * myTab;
@property (weak, nonatomic) IBOutlet UITextField *mailTF;
@property(nonatomic,retain)NSMutableArray * dataArr;
@property(nonatomic,retain)PRClientNameTableView * nameView;
@end

@implementation PRAddNewRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTitle = self.editModel?@"编辑":@"新增";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.topHeight.constant = kTopHeight;
    self.botHeight.constant = KTabbarSafeBottomMargin + 80;
    self.sendSelBtn = self.unSendBtn;
    self.paySelBtn = self.unPayBtn;
    self.viewWidth.constant = IPHONE_WIDTH;
    
    self.nameTF.delegate = self;
    [_nameTF addTarget:self action:@selector(textFieldDidChangeValue:)  forControlEvents:UIControlEventEditingChanged];
    self.sendSelBtn = self.unSendBtn;
    self.paySelBtn = self.unPayBtn;
    [self createTab];
    if (self.editModel) {
        [self configEditData];
        self.rightBtnName = @"删除";
        self.rightBtnFontSize = 14;
        self.rightBtnNameColor = [UIColor blackColor];
    }
    
}
- (void)rightBtnClick{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(bg_primaryKey),self.editModel.bg_id];
    [PRMainViewModel bg_delete:GoodsInfoTab where:where];
    if (self.saveBlock) {
        self.saveBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)createTab{
    CGRect frame = CGRectZero;
    self.dataArr = [NSMutableArray new];
    if (self.editModel) {
        [self.dataArr addObjectsFromArray:self.editModel.goodsInfoArr.copy];
        frame = Frame(0, 0, IPHONE_WIDTH, 30 * self.dataArr.count);
        self.goodContainHeight.constant = self.dataArr.count * 30;
    }else{
        frame = Frame(0, 0, IPHONE_WIDTH, 30);
        GoodsInfoModel * mo = [GoodsInfoModel new];
        [self.dataArr addObject:mo];
    }
    
    self.myTab = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
    _myTab.delegate = self;
    _myTab.dataSource = self;
    _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myTab.scrollEnabled = NO;
    _myTab.rowHeight = 30;
    [self.goodContainView addSubview:self.myTab];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self.view addSubview:self.nameView];
    self.nameView.hidden = YES;//刚开始都hidden
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.nameView.hidden = YES;
}
- (void)textFieldDidChangeValue:(UITextField*)textField{
    if (!self.nameView.isEmptyTab) {
        if (textField.text.length > 0 && !self.nameView.isEmptyTab) {
            self.nameView.hidden = NO;
            [self.nameView filterInput:textField.text];
        }else{
            self.nameView.hidden = YES;
        }
    }
}
-(void)configEditData{
    self.nameTF.text = self.editModel.person;
    self.phoneTF.text = self.editModel.phone;
    self.remarkTV.text = self.editModel.remark;
    self.mailTF.text = self.editModel.mailFee;
    if ([self.editModel.isSend isEqualToString:@"未发货"]) {
        self.unSendBtn.selected = YES;
        self.sendedBtn.selected = NO;
        self.sendSelBtn = self.unSendBtn;
    }else{
        self.sendedBtn.selected = YES;
        self.unSendBtn.selected = NO;
        self.sendSelBtn = self.sendedBtn;
    }
    if ([self.editModel.guestIsPay isEqualToString:@"未付款"]) {
        self.unPayBtn.selected = YES;
        self.payedBtn.selected = NO;
        self.paySelBtn = self.unPayBtn;
    }else{
        self.unPayBtn.selected = NO;
        self.payedBtn.selected = YES;
        self.paySelBtn = self.payedBtn;
    }
    self.orderCreateTimeLab.text = self.editModel.createTime;
    self.orderCreateTimeLab.hidden = NO;
    self.choseTimeBtn.hidden = YES;
    self.currentTimeBtn.hidden = YES;
}

- (IBAction)currentTimeBtnClick:(id)sender {
    NSString * time = @"自定义时间";
    [self.choseTimeBtn setTitle:time forState:UIControlStateNormal];
    self.choseBtnWidth.constant = 80;
    self.currentTimeBtn.selected = YES;
}

- (IBAction)choseTimeBtnClick:(id)sender {
    PGDatePickManager *mgr = [[PGDatePickManager alloc]init];
    mgr.style = PGDatePickManagerStyleSheet;
    mgr.isShadeBackground = YES;
    mgr.cancelButtonTextColor = [UIColor darkGrayColor];
    mgr.headerViewBackgroundColor = [UIColor groupTableViewBackgroundColor];
    PGDatePicker *datePicker = mgr.datePicker;
    datePicker.datePickerMode = PGDatePickerModeDateHourMinute;
    datePicker.textColorOfSelectedRow = [UIColor blackColor];
    datePicker.textColorOfOtherRow = [UIColor lightGrayColor];
    datePicker.lineBackgroundColor = [UIColor darkGrayColor];
    datePicker.delegate = self;
    [self presentViewController:mgr animated:false completion:nil];
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSString * time = [NSString stringWithFormat:@"%ld年%02ld月%02ld日%02ld时%02ld分",dateComponents.year,dateComponents.month,dateComponents.day,dateComponents.hour,dateComponents.minute];
    CGFloat width = [time sizeWithFont:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(IPHONE_WIDTH, 20)].width;
    [self.choseTimeBtn setTitle:time forState:UIControlStateNormal];
    self.choseBtnWidth.constant = width + 10;
    self.currentTimeBtn.selected = NO;
}

- (IBAction)unSendClick:(UIButton *)sender {
    [self configSendBtn:sender];
}
- (IBAction)sendBtnClick:(UIButton *)sender {
    [self configSendBtn:sender];
}
-(void)configSendBtn:(UIButton*)sender{
    sender.selected = !sender.selected;
    self.sendSelBtn.selected = !self.sendSelBtn.selected;
    self.sendSelBtn = sender;
}
- (IBAction)unPayClick:(id)sender {
    [self cofigPayBtn:self.unPayBtn];
}
- (IBAction)payClick:(UIButton *)sender {
    [self cofigPayBtn:sender];
}
-(void)cofigPayBtn:(UIButton*)sender{
    sender.selected = !sender.selected;
    self.paySelBtn.selected = !self.paySelBtn.selected;
    self.paySelBtn = sender;
}
- (IBAction)saveBtnClick:(id)sender {
    PRMainViewModel * mo = nil;
    if (self.editModel) {
        mo = self.editModel;
    }else{
        mo = [PRMainViewModel new];
    }
    
    mo.goodsInfoArr = self.dataArr;
    mo.person = self.nameTF.text;
    mo.phone = self.phoneTF.text;
    mo.mailFee = self.mailTF.text;
    if (self.editModel) {
        //如果是修改的就不改变创建时间
        mo.modifyTime = self.choseTimeBtn.titleLabel.text;
    }else{
        if (self.currentTimeBtn.isSelected) {
            NSDate * date = [NSDate date];
            mo.createTime = [NSString stringWithFormat:@"%ld年%02ld月%02ld日%02ld时%02ld分",date.year,date.month,date.day,date.hour,date.minute];
        }else{
            mo.createTime = self.choseTimeBtn.titleLabel.text;
        }
    }
    
    mo.isSend = self.sendSelBtn.titleLabel.text;
    mo.guestIsPay = self.paySelBtn.titleLabel.text;
    mo.remark = self.remarkTV.text;
    mo.bg_tableName = GoodsInfoTab;
    [mo bg_saveOrUpdate];
    if (self.saveBlock) {
        self.saveBlock();
    }
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"name"),bg_sqlValue(self.nameTF.text)];
    NSArray* arr = [PRClientDataModel bg_find:ClientNameTab where:where];
    if (arr.count == 0) {
        PRClientDataModel * client = [PRClientDataModel new];
        client.name = self.nameTF.text;
        client.phone = self.phoneTF.text;
        client.bg_tableName = ClientNameTab;
        [client bg_saveAsync:^(BOOL isSuccess) {
            if (!isSuccess) {
                [client bg_save];
            }
        }];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PRAddNewRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[PRAddNewRecordCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.generBlock = ^(BOOL isUp) {
        if (isUp) {
            GoodsInfoModel * mo = [GoodsInfoModel new];
            [self.dataArr addObject:mo];
            tableView.height = self.dataArr.count* 30;
            self.goodContainHeight.constant = self.dataArr.count * 30;
            [tableView reloadData];
        }        
    };
    cell.model = self.dataArr[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (PRClientNameTableView *)nameView{
    if (!_nameView) {
        _nameView = [[PRClientNameTableView alloc]initWithFrame:Frame(self.nameTF.mm_minX, self.nameTF.mm_maxY + kTopHeight+2, self.nameTF.mm_w, 45)];
        _nameView.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:[UIColor darkGrayColor]];
        MJWeakSelf
        _nameView.choseNameClick = ^(PRClientDataModel * _Nonnull mo) {
            weakSelf.nameTF.text = mo.name;
            weakSelf.phoneTF.text = mo.phone;
        };
    }
    return _nameView;
}
@end
